package com.lyc.platform.server.gateway.util;

import com.lyc.platform.server.gateway.bean.Connection;
import com.lyc.platform.server.gateway.consts.Const;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 对于连接有关的工具类
 *
 * @author liangyucheng
 */
public class ConnetctionUtil {
    public static final ConcurrentHashMap<String, Connection> connections = new ConcurrentHashMap<>();

    /**
     * 将设备id和channel绑定起来
     * 可以通过设备id找到对应的channel,并进行数据下发.
     *
     * @param connection 连接
     */
    public void addConnection(Connection connection) {
        connections.put(connection.getDeviceId(), connection);
        connection.getChannel().attr(Const.connection).set(connection);
    }

    public Connection getConnection(String deviceId) {
        return connections.get(deviceId);
    }

    public void logout(Connection connection) {
        connections.remove(connection.getDeviceId());
        Connection thisConnection = connection.getChannel().attr(Const.connection).get();
        thisConnection.getChannel().close();
    }

    public void write(byte[] rec, Connection connection) {
        connection.getChannel().writeAndFlush(rec);
    }

}
